import React, {PropsWithChildren, useCallback, useState} from "react"
import {Button, Form, FormItemProps, Row, Select} from "antd";
import FormItem from "antd/es/form/FormItem";
import {ReloadOutlined} from "@ant-design/icons";
import {FormInstance} from "antd/es/form/hooks/useForm";

export interface RefreshableFormItemProps {
    label?: string
    name?: string
    onRefresh?: () => Promise<any>
    loading?: boolean
    builder: (refreshing: boolean) => React.ReactNode
    required?: boolean
    appendRender?: (form: FormInstance) => React.ReactNode
    dependencies?:FormItemProps["dependencies"]
}

const RefreshableSelectFormItem: React.FC<RefreshableFormItemProps> = (props) => {
    const {
        builder,
        label,
        name,
        onRefresh,
        loading,
        required,
        appendRender
    } = props
    const [onRefreshLoading, setOnRefreshLoading] = useState(false)
    let computedLoading = loading === undefined ? onRefreshLoading : loading;
    const buildFormItemChildren = useCallback((form?: FormInstance) => {
        return <Row>
            <FormItem name={name}>
                {builder(computedLoading)}
            </FormItem>
            <Button shape={"circle"} type={"text"} loading={computedLoading}
                    icon={<ReloadOutlined/>} onClick={async () => {
                if (onRefresh) {
                    setOnRefreshLoading(true)
                    try {
                        await onRefresh()
                    } finally {
                        setOnRefreshLoading(false)
                    }
                }
            }}/>
            {!!form && !!appendRender ? appendRender(form) : undefined}
        </Row>
    }, [appendRender,builder,onRefresh,computedLoading,name])
    return (
        <>
            <Form.Item dependencies={props.dependencies} label={label} required={required}>
                {!!props.dependencies?.length ? (form) => {
                    return buildFormItemChildren(form)
                } : buildFormItemChildren()}
            </Form.Item>
        </>
    )
}

export default RefreshableSelectFormItem
